package ctrl

/*******************************************************************************
Copyright:cloud
Author:cloudapex@126.com
Version:1.0
Date:2020-06-12
Description: 缓存控制器
*******************************************************************************/
import (
	"permis/conf"

	"gitee.com/cloudapex/ulern/cto"
	"gitee.com/cloudapex/ulern/rds"
)

var RDB *rdb

func init() { RDB = cto.Install("MC_MyRds", &rdb{}).(*rdb) }

type rdb struct {
	cto.ControlBase

	hands []*rds.Pool
}

func (this *rdb) HandleInit() {
	this.ControlBase.HandleInit()
	this.startConnect()
}
func (this *rdb) HandleTerm() {
	for _, c := range this.hands {
		c.Close()
	}
	this.ControlBase.HandleTerm()
}

// -------- public

func (this *rdb) Use(nIndex int) *rds.Pool {
	if len(this.hands) >= nIndex {
		return this.hands[nIndex]
	}
	return nil
}

// -------- internal
func (this *rdb) startConnect() {
	this.Infov("Connecting to redis server...")

	for _, cnf := range conf.DB.RDBs() {
		this.Tracev(cnf.HostAddr, cnf.DbIdx)

		hand, err := rds.InitRds(&cnf)
		if err != nil {
			this.Fatalv(err)
		}
		this.hands = append(this.hands, hand)
	}
}
